<template>
	<view
		class="u-refresh"
		:style="{transform: `translate3d(0, ${top}px, 0)`}"
		@touchstart="touchStart"
		@touchmove="touchMove"
		@touchend="touchEnd"
	>
		<view class="refresh-box">
			<view class="refresh-moudle">
				<slot></slot>
			</view>
		</view>
		
		<slot name="page"></slot>
	</view>
</template>

<script>
	/**
	 * u-refresh 自定义下拉刷新
	 * @property {Number} defaultOffset 控制下拉触发高度
	 * @property {Number} refreshTime 刷新时间（毫秒）
	 * 
	 * @event {Function(start)} change 刷新状态
	 */
	export default {
		name: 'u-refresh',
		props: {
			// 控制下拉触发高度
			defaultOffset: {
				type: Number,
				default: 80
			},
			goPageHeight: {
				type: Number,
				default: 150
			},
			refreshTime: {
				type: Number,
				default: 1000
			}
		},
		data () {
			return {
				top: 0, // 页面滑动的距离
				startY: 0, // 记录初始点击，在页面上的位置
				footprintShow: false // 是否正在下拉刷新
			}
		},
		methods: {
			// 手指触碰到元素触发
			touchStart (e) {
				if (this.footprintShow) return false

				// 相对于父元素的距离
				this.startY = e.changedTouches[0].pageY
			},
			// 手指滑动事件
			touchMove (e) {
				if (this.footprintShow) return false

				let diff = e.changedTouches[0].pageY - this.startY
				// Math.pow(3, 7) -- 3**7
				this.top = Math.pow(diff, 0.9)
				// this.top = Math.pow(diff, 0.75) + (this.dropDownState === 3 ? this.defaultOffset : 0)
				
				// 判断是否到达触发高度
				if (this.top >= this.defaultOffset) {
					// 触发刷新
					this.$emit('stateChage', 2)
					e.preventDefault()
				} else {
					// 没有触发刷新
					this.$emit('stateChage', 1)
					// 去掉会导致 ios 无法刷新
					e.preventDefault()
				}
			},
			// 手指松开事件
			touchEnd (e) {
				if (this.footprintShow) return false

				if (this.top >= this.goPageHeight) {
					this.$emit('stateChage', 4)
					this.top = 0;
				} else if (this.top >= this.defaultOffset) {
					this.$emit('stateChage', 3)
					this.top = this.defaultOffset
					this.footprintShow = true
					this.footprintEvent()
				} else {
					this.$emit('stateChage', 1)
					this.top = 0;
				}
			},
			// 结束刷新状态
			footprintEvent () {
				setTimeout(() => {
					this.$emit('stateChage', 1)
					this.top = 0;
					this.footprintShow = false;
				}, this.refreshTime)
			}
		}
	}
</script>

<style lang="scss" scoped>
.u-refresh {
	.refresh-box {
		position: relative;
		.refresh-moudle {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			-webkit-overflow-scrolling: touch; /* ios5+ */
		}
	}
}
</style>
